﻿using System;
using System.IO;
using System.Web;
using System.Collections.Generic;

using E.Model;
using E.BLL;
using E.Web.UI.Page;

using X.Common;
using E.Enum;

namespace E.Web.Teacher.internals.question
{
    public partial class Edit : TeacherBasePage
    {
        public string act;
        public int id;
        public QuestionModel model = new QuestionModel();
        public IList<QuestionCategoryModel> categoryList;
        public Dictionary<int, string> courseList;
        public IList<DictAreaModel> areaList;
        public int count = 0;
        public string area_v;

        public int cid;

        protected override void ShowPage()
        {
            act = XRequest.GetString("act");
            id = XRequest.GetInt("id", -1);
            cid = XRequest.GetInt("cid", -1);

            string oldPicFilePath = XRequest.GetString("o_p_p");
            string oldSoundFilePath = XRequest.GetString("o_s_p");
            //id = 1;

            areaList = GetTeacherAreaList(teacherid);

            QuestionBLL bll = new QuestionBLL();

            if (!ispost)
            {
                courseList = (new CourseBLL()).GetCourseListByTeacherID(teacherid);
                categoryList = bll.GetAllQuestionCategoryModel();
            }

            if (act == "u" && id != -1)
            {
                model = bll.GetQuestionInfo(id);
                area_v = Convert2String(model.AreaList);
                if (model.OptionList != null && model.OptionList.Count > 0)
                {
                    count = model.OptionList.Count;
                }
            }

            if (ispost)
            {
                string[] chk = XRequest.GetString("chk_v").Split(',');
                string area = XRequest.GetString("area_v");
                string[] areas = GetArray(area);
                int optionCount = XRequest.GetInt("ItemCountSlt", -1);
                IList<QuestionOptionModel> optionList = new List<QuestionOptionModel>();

                model = new QuestionModel();
                model.Title = XRequest.GetString("TitleTxt");
                model.CategoryID = XRequest.GetInt("CategorySlt", -1);
                model.Score = XRequest.GetInt("ScoreTxt", -1);
                model.Description = XRequest.GetString("DescriptionTxt");
                model.KnowledgePoint = XRequest.GetString("KnowledgePointTxt");
                model.CourseID = XRequest.GetInt("CourseSlt", -1);
                model.IsRequired = XRequest.GetInt("IsRequiredSlt", 0) == 0 ? false : true;
                model.AddDate = DateTime.Now;
                model.AreaIDArray = areas;

                model.ImgUrl = "";
                model.SoundUrl = "";

                //如果是主观题，置选项数为-1
                if (model.CategoryID == (int)EnumQuestionCategory.FITBs || model.CategoryID == (int)EnumQuestionCategory.SAQs)
                    optionCount = -1;

                HttpPostedFile picFile = HttpContext.Current.Request.Files["PicFileUpload"];
                HttpPostedFile soundFile = HttpContext.Current.Request.Files["SoundFileUpload"];

                string host = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
                string picFilePath = "";
                string soundFilePath = "";
                bool fileErr = false;
                bool hasFile = false;
                string serverPath = System.Web.HttpContext.Current.Server.MapPath("/");

                string msg = "";

                #region file handle

                #region pic

                if (picFile.ContentLength > 0)
                {
                    if (picFile.ContentLength < config.FileUpLoadMaxLength && !picFile.FileName.ToLower().Equals(soundFile.FileName.ToLower()))
                    {
                        hasFile = true;
                        string fullName = picFile.FileName;
                        string fileName = fullName;
                        if (fullName.IndexOf('\\') != -1)
                        {
                            fileName = fullName.Substring(fullName.LastIndexOf('\\') + 1);
                        }
                        picFilePath = "upload\\pic\\" + fileName;

                        string scheme = HttpContext.Current.Request.Url.Scheme;
                        model.ImgUrl = scheme + "://" + host + "/upload/pic/" + fileName;


                        if (File.Exists(serverPath + picFilePath))
                        {
                            fileErr = true;
                            msg = "文件已经存在";
                        }
                        else
                        {
                            try
                            {
                                picFile.SaveAs(serverPath + picFilePath);
                            }
                            catch (IOException IoEx)
                            {
                                fileErr = true;
                                msg = IoEx.Message;
                            }
                            catch (Exception ex)
                            {
                                fileErr = true;
                                msg = ex.Message;
                            }
                        }
                    }
                    else
                    {
                        fileErr = true;
                        msg = "文件错误";
                    }
                }

                #endregion

                #region sound

                if (soundFile.ContentLength > 0)
                {
                    if (soundFile.ContentLength < config.FileUpLoadMaxLength && !picFile.FileName.ToLower().Equals(soundFile.FileName.ToLower()))
                    {
                        hasFile = true;
                        string fullName = soundFile.FileName;
                        string fileName = fullName;
                        if (fullName.IndexOf('\\') != -1)
                        {
                            fileName = fullName.Substring(fullName.LastIndexOf('\\') + 1);
                        }
                        soundFilePath = "upload\\sound\\" + fileName;

                        string scheme = HttpContext.Current.Request.Url.Scheme;
                        model.SoundUrl = scheme + "://" + host + "/upload/sound/" + fileName;

                        if (File.Exists(serverPath + soundFilePath))
                        {
                            fileErr = true;
                            msg = "文件已经存在";
                        }
                        else
                        {
                            try
                            {
                                soundFile.SaveAs(serverPath + soundFilePath);
                            }
                            catch (IOException IoEx)
                            {
                                fileErr = true;
                                msg = IoEx.Message;
                            }
                            catch (Exception ex)
                            {
                                fileErr = true;
                                msg = ex.Message;
                            }
                        }
                    }
                    else
                    {
                        fileErr = true;
                        msg = "文件错误";
                    }
                }

                #endregion

                #endregion

                if (fileErr)
                {
                    //Alert("文件传输错误，请稍后再试");
                    string href = "";
                    if (act == "u")
                    {
                        href = " window.location = '/internals/question/Edit.aspx?act=u&id=" + id + "';";
                    }
                    else
                    {
                        href = "history.back();";
                    }

                    //    if (act == "u")
                    //    { 
                    //        ExecuteJS(" window.location = '/exam/QuestionEdit.aspx?act=u&id=" + id + "';");
                    //    }

                    ExecuteJS("alert('" + msg + "'); " + href);
                }
                else
                {
                    int rst = 0;
                    string href = "";

                    switch (act)
                    {
                        case "n":
                            for (int i = 0; i < optionCount; i++)
                            {
                                QuestionOptionModel optionModel = new QuestionOptionModel();
                                optionModel.OptionTitle = XRequest.GetString("option_" + i);
                                optionModel.SerialNumber = i + 1;
                                optionModel.IsCorrect = chk[i] == "1" ? true : false;
                                optionList.Add(optionModel);
                            }
                            model.OptionList = optionList;

                            rst = bll.AddQuestion(model);
                            href = "/internals/question/Edit.aspx?act=n&cid=" + model.CourseID;

                            break;
                        case "u":
                            model.ID = id;

                            for (int i = 0; i < optionCount; i++)
                            {
                                QuestionOptionModel optionModel = new QuestionOptionModel();
                                optionModel.ID = id;
                                optionModel.OptionTitle = XRequest.GetString("option_" + i);
                                optionModel.SerialNumber = i + 1;
                                optionModel.IsCorrect = chk[i] == "1" ? true : false;
                                optionList.Add(optionModel);
                            }
                            model.OptionList = optionList;

                            rst = bll.UpdateQuestion(model);
                            href = "/internals/question/Edit.aspx?act=u&id=" + id;

                            break;
                        default: break;
                    }

                    if (rst > 0)
                    {
                        if (act == "u")
                        {
                            try
                            {
                                if (!oldPicFilePath.Equals(""))
                                {
                                    string nohttp_pic = oldPicFilePath.Substring(oldPicFilePath.IndexOf("//") + 2);
                                    File.Delete(serverPath + nohttp_pic.Substring(nohttp_pic.IndexOf("/")));
                                }
                                if (!oldSoundFilePath.Equals(""))
                                {
                                    string nohttp_sound = oldSoundFilePath.Substring(oldSoundFilePath.IndexOf("//") + 2);
                                    File.Delete(serverPath + nohttp_sound.Substring(nohttp_sound.IndexOf("/")));
                                }
                            }
                            catch (IOException ioe)
                            { }
                            catch (Exception ex)
                            { }
                        }
                        Alert("操作成功");
                        ExecuteJS("window.location = '" + href + "';");
                    }
                    else
                    {
                        Alert("操作失败");
                        try
                        {
                            File.Delete(picFilePath);
                            File.Delete(soundFilePath);
                        }
                        catch (IOException ioe)
                        { }
                        catch (Exception ex)
                        { }
                    }
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}
